<template>
  <div>
    <h3>文章列表页面</h3>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="6">
          <a-input-search v-model="queryParam.title"  allowClear @search="searchArt" placeholder="输入文章名查找" enterButton></a-input-search>
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="$router.push(`/admin/addArt`)">新增</a-button>
        </a-col>
        <a-col :span="3">
          <a-select placeholder="请选择分类" style="width: 200px" @change="CateChange">
            <a-select-option
              v-for="item in Catelist"
              :key="item.id"
              :value="item.id"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="1">
          <a-button type="info" @click="getArtList()">显示全部</a-button>
        </a-col>
      </a-row>
      <a-table
      rowKey="ID"
      :columns="columns"
      :pagination='paginationOption'
      :dataSource="Artlist"
       bordered
       @change="handleTableChange"
       >
       <span slot="UpdateAt" slot-scope="UpdateAt">{{ UpdateAt | filterTime(UpdateAt) }}</span>
       <span class="ArtImg" slot="img" slot-scope="img">
        <img :src="img" />
       </span>
        <span slot="role" slot-scope="role">{{ role === 1 ? '热点':'推荐'}}</span>
        <template slot="action" slot-scope="data">
          <div class="actionSlot">
             <a-button type="primary" icon="edit" style="margin-right:15px" @click='$router.push(`/admin/addart/${data.ID}`)'>编辑</a-button>
             <a-button type="danger" icon="delete" style="margin-right:15px" @click="deleteCate(data.ID)">删除</a-button>
        </div>
      </template>
      </a-table>
    </a-card>
    <!-- 编辑分类区域 -->
    <a-modal width="60%" closable title="编辑分类" :visible="editCateVisible"  @ok="editCateOK" @cancel="editCateCancel" destroyOnClose>
      <a-form-model :model="CateInfo" :rules="CateRules" ref="addCateRef">
        <a-form-model-item label="用户名" prop="name">
          <a-input v-model="CateInfo.name"></a-input>
        </a-form-model-item>
        <a-form-model-item label="是否为推荐">
          <a-switch
            :checked="IsAdmin"
            checked-children="是"
            un-checked-children="否"
            @change="adminChange"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
// import day from 'dayjs'
import moment from 'moment'

const columns = [
  {
    title: 'ID',
    dataIndex: 'ID',
    width: '10%',
    key: 'id',
    align: 'center'
  }, {
    title: '更新日期',
    dataIndex: 'UpdateAt',
    width: '10%',
    key: 'UpdateAt',
    align: 'center',
    scopedSlots: { customRender: 'UpdateAt' }
    // scopedSlots: {
    //   customRender: (val) => {
    //     console.log(val)
    //     return val ? day(val).format('YYYY年MM月DD日 HH:mm') : '暂无'
    //   }
    // }
  }, {
    title: '分类',
    dataIndex: 'Category.name',
    width: '10%',
    key: 'name',
    align: 'center'
  }, {
    title: '文章标题',
    dataIndex: 'title',
    width: '20%',
    key: 'title',
    align: 'center',
    scopedSlots: { customRender: 'title' }
  }, {
    title: '文章描述',
    dataIndex: 'desc',
    width: '20%',
    key: 'desc',
    align: 'center',
    scopedSlots: { customRender: 'desc' }
  }, {
    title: '缩略图',
    dataIndex: 'img',
    width: '15%',
    key: 'img',
    align: 'center',
    scopedSlots: { customRender: 'img' }
  }, {
    title: '操作',
    width: '30%',
    key: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  data () {
    return {
      paginationOption: {
        pageSizeOptions: ['5', '10', '20'],
        pageSize: 5,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共${total}条`
      },
      Catelist: [],
      Artlist: [],
      columns,
      queryParam: {
        title: '',
        pagesize: 5,
        pagenum: 1
      },
      CateInfo: {
        id: 0,
        name: '',
        title: '',
        desc: '',
        img: '',
        role: 2
      },
      newCate: {
        name: '',
        title: '',
        desc: '',
        img: '',
        role: 2
      },
      visible: false,
      CateRules: {
        name: [{ required: true, message: '请输入分类名', trigger: 'blur' }, { min: 4, max: 12, message: '用户名应当在4到12个字符之间', trigger: 'blur' }]
      },
      addCateRules: {
        name: [
          {
            validator: (rule, value, callback) => {
              if (this.newCate.ename === '') {
                callback(new Error('请输入分类名'))
              }
              if ([...this.newCate.name].length < 4 || [...this.newCate.name].length > 12) {
                callback(new Error('分类名应当在4到12个字符之间'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      editCateVisible: false
    }
  },
  created () {
    this.getArtList()
    this.getCateList()
  },
  computed: {
    IsAdmin: function () {
      if (this.CateInfo.role === 1) {
        return true
      } else {
        return false
      }
    }
  },
  methods: {
    async getArtList () {
      console.log(this.paginationOption)
      const { data: res } = await this.$http.get('article', {
        params: {
          title: this.queryParam.title,
          pagesize: this.queryParam.pagesize,
          pagenum: this.queryParam.pagenum
        }
      })
      console.log(res)
      if (res.status !== 200) {
        return this.$message.error(res.message)
      } else {
        this.Artlist = res.data
        this.paginationOption.total = res.total
      }
    },
    async getCateList () {
      console.log(this.paginationOption)
      const { data: res } = await this.$http.get('admin/category')
      if (res.status !== 200) {
        return this.$message.error(res.message)
      } else {
        this.Catelist = res.data
      }
    },
    // 搜索文章
    async searchArt () {
      this.queryParam.pagenum = 1
      this.queryParam.current = 1
      const { data: res } = await this.$http.get('article', {
        params: {
          title: this.queryParam.title,
          pagesize: this.queryParam.pagesize,
          pagenum: this.queryParam.pagenum
        }
      })
      if (res.status !== 200) return this.$message.error(res.message)
      this.Catelist = res.data
      this.paginationOption.total = res.total
    },
    // 更改分页
    handleTableChange (paginationOption, filters, sorter) {
      var pager = { ...this.pageSizeOptions }
      pager.current = paginationOption.current
      pager.pageSize = paginationOption.pageSize
      this.queryParam.pageSize = paginationOption.pageSize
      this.queryParam.pagenum = paginationOption.current
      if (paginationOption.pageSize !== this.paginationOption.pageSize) {
        this.queryParam.pagenum = 1
        pager.current = 1
      }
      this.paginationOption = pager
      this.getCateList()
    },
    // 删除用户
    deleteCate (id) {
      this.$confirm({
        title: '提示：请再次确认',
        content: '确定要删除该文章吗？一旦删除，无法恢复',
        onOk: async () => {
          const { data: res } = await this.$http.delete(`article/${id}`)
          console.log(res)
          if (res.status !== 200) return this.$message.error(res.message)
          this.$message.success('删除成功')
          this.getArtList()
        },
        onCancel: () => {
          this.$message.info('已取消删除')
        }
      })
    },
    // 查询分类下的文章
    CateChange (value) {
      this.getCateArt(value)
    },
    adminChange (vaule) {
      this.CateInfo.role = Number(vaule)
    },
    // 编辑用户
    async editCate (id) {
      this.editCateVisible = true
      const { data: res } = await this.$http.get(`Cate/${id}`)
      this.CateInfo = res.data
      this.CateInfo.id = id
    },
    editCateOK () {
      this.$refs.addCateRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('参数不符合要求，请重新输入')
        } else {
          const { data: res } = await this.$http.put(`Cate/${this.CateInfo.id}`, {
            Catename: this.CateInfo.Catename,
            role: this.CateInfo.role
          })
          if (res.status !== 200) {
            this.$message.error(res.message)
          } else {
            this.editCateVisible = false
            this.$message.success('更新用户信息成功')
            this.getCateList()
          }
        }
      })
    },
    editCateCancel () {
      this.$refs.addCateRef.resetFields()
      this.editCateVisible = false
      this.$message.info('编辑已取消')
    },
    async ChangePassword (id) {
      this.changePasswordVisible = true
      const { data: res } = await this.$http.get(`Cate/${id}`)
      this.changePassword.role = res.data.role
      this.changePassword.id = id
    },
    changePasswordOk () {
      this.$refs.changePasswordRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('参数不符合要求，请重新输入')
        } else {
          const { data: res } = await this.$http.put(`admin/changepw/${this.changePassword.id}`, {
            password: this.changePassword.password
          })
          if (res.status !== 200) {
            this.$message.error(res.message)
          } else {
            this.changePasswordVisible = false
            this.$message.success('更新用户信息成功')
            this.getCateList()
          }
        }
      })
    },
    changePasswordCancel () {
      this.$refs.changePasswordRef.resetFields()
      this.changePasswordVisible = false
      this.$message.info('修改已取消')
    }
  },
  filters: {
    filterTime (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style scoped>
.actionSlot{
display: flex;
justify-content: center;
}
.ArtImg {
  width: 100%;
  height: 100%;
  overflow:hidden;
  background-size: cover;
  background-position: center;
}
.ArtImg img {
  height: 90px;
}
</style>
